package servlet;

import myutil.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码
        try {
            HttpSession session = request.getSession();//获取session
            String validate1 = request.getParameter("validate");    //获取输入框的验证码
            String validate2 = (String) session.getAttribute("validateCode");   //获取session 的验证码
            System.out.println("v1 "+validate1);
            System.out.println("v2 "+validate2);
            //session.removeAttribute("validateCode");    //删除session 验证码

            String name = request.getParameter("userName");
            String password = request.getParameter("password");
            String test = request.getParameter("test");     //获取 自动登陆单选框的值
            String name1 = null;
            String password1= null;
            Connection conn = DBUtil.getConn();    //调用 DB类的 getConn()方法  加载驱动 连接数据库
            Statement statement = conn.createStatement();
            if(name != null && !name.equals("")&& !password.equals("")){    //判断输入值 name password 是否为空
                // 不为空则将 name password 进行编码  解码
                boolean yzm =validate1.equals(validate2);
                if (yzm==false){        //判断验证码
                    request.setAttribute("err","665");
                    request.getRequestDispatcher("/login.jsp").forward(request,response);
                    return;
                }
                name1= URLEncoder.encode(name,"utf-8");//编码   保存cookie
                name = URLDecoder.decode(name1,"UTF-8");//解码    校验
                password1= URLEncoder.encode(password,"utf-8");//编码
                password = URLDecoder.decode(password1,"UTF-8");//解码
                //查询数据库 校验
                String sql = "select * from user where name ='" + name + "' and password=" + password;
                System.out.println(sql);
                ResultSet resultSet = statement.executeQuery(sql);
                if(resultSet != null){
                    // 登录成功
                    request.getSession().setAttribute("userName", name);
                    session.setMaxInactiveInterval(600);
                    if (test != null) {                 //单选框不为 null   将账号密码 生成 Cookie
                        Cookie cookie1 = new Cookie("name", name1);
                        Cookie cookie2 = new Cookie("password", password1);

                        cookie1.setMaxAge(7 * 24 * 60 * 60);    //设置cookie保存的时间
                        cookie1.setPath(request.getContextPath() + "/");
                        cookie2.setMaxAge(7 * 24 * 60 * 60);
                        cookie2.setPath(request.getContextPath() + "/");
                        response.addCookie(cookie1);
                        response.addCookie(cookie2);
                    }
                    // 跳转
                    String sql1 = riz(request, name);
                    statement.execute(sql1);

                    System.out.println("登录成功");
                    response.sendRedirect("my_home.jsp");

                }else {
                    // 用户名错误
                    request.setAttribute("err", "666");
                    request.getRequestDispatcher("/login.jsp").forward(request,response);

                }
            }else {
                //为空 则 获取cookie
                Cookie[] cookies = request.getCookies();
                for (Cookie cookie : cookies) {      //遍历cookie
                    String cookieName = cookie.getName();
                    if (cookieName.equals("name")) { //判断cookie的 name 是否等于"name"
                        name = cookie.getValue();   //将name为"name"的cookie 的值 赋给 name
                        name = URLDecoder.decode(name, "UTF-8");//解码
                    } else if (cookieName.equals("password")) {
                        //判断cookie的 name 是否等于"password"
                        password = cookie.getValue();   //将name为"password"的cookie 的值 赋给 password
                        password = URLDecoder.decode(password, "UTF-8");//解码
                    }
                }
                if (name == null || name.equals("") || password.equals("")) {
//                    request.setAttribute("err", "666");
//                    request.getRequestDispatcher("/login.jsp").forward(request, response);
//                    return;
                    response.getWriter().write("fail");
                    return;
                }
                String sql = "select * from user where name ='" + name + "' and password=" + password;
                System.out.println(sql);
                ResultSet resultSet = statement.executeQuery(sql);
                if (resultSet != null) {
                    request.getSession().setAttribute("userName", name);
                    session.setMaxInactiveInterval(600);

                    String sql1 = riz(request, name);
                    statement.execute(sql1);
                    System.out.println("登录成功");
                    //response.sendRedirect("my_home.jsp");
                    response.getWriter().write("success");

                }else {
                    // 用户名错误
                    request.setAttribute("err", "666");
                    response.getWriter().write("fail");
                    //request.getRequestDispatcher("/login.jsp").forward(request,response);
                }

            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }
    //日志记录，账户登录时间登录的ip，登录的名字
    private String riz(HttpServletRequest req,String name){
        //当前时间
        java.util.Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(date);
        //访问人ip
        String ip = req.getRemoteAddr();
        //记录账户名字与时间
        String sql1="INSERT INTO rz(ip,rname,rtime) value('"+ip+"','"+name+"','"+format+"')";
        return sql1;
    }

}


